<?php

declare(strict_types=1);

use think\facade\Db;
use think\migration\Migrator;

class UpdateProdTableStructure extends Migrator
{
    public function up(): void
    {
        $table = $this->table('prod');

        if ($table->hasColumn('org_id') && !$table->hasColumn('seller_org_id')) {
            $table->renameColumn('org_id', 'seller_org_id');
        }

        if (!$table->hasColumn('seller_user_id')) {
            $table->addColumn('seller_user_id', 'integer', [
                'signed' => false,
                'null' => true,
                'comment' => '卖家用户ID',
                'after' => 'seller_org_id',
            ]);
        }

        if (!$table->hasColumn('region_id')) {
            $table->addColumn('region_id', 'integer', [
                'signed' => false,
                'null' => true,
                'comment' => '所属区域',
                'after' => 'seller_user_id',
            ]);
        }

        if ($table->hasColumn('name') && !$table->hasColumn('title')) {
            $table->renameColumn('name', 'title');
        }

        if ($table->hasColumn('spu_code') && !$table->hasColumn('sku_code')) {
            if ($table->hasIndex(['spu_code'])) {
                $table->removeIndex(['spu_code']);
            }
            $table->renameColumn('spu_code', 'sku_code');
            $table->addIndex(['sku_code'], ['unique' => true, 'name' => 'idx_prod_sku_code']);
        }

        if (!$table->hasColumn('subtitle')) {
            $table->addColumn('subtitle', 'string', [
                'limit' => 255,
                'default' => '',
                'comment' => '副标题',
                'after' => 'title',
            ]);
        }

        if (!$table->hasColumn('model')) {
            $table->addColumn('model', 'string', [
                'limit' => 120,
                'default' => '',
                'comment' => '型号',
                'after' => 'subtitle',
            ]);
        }

        if ($table->hasColumn('cover_url') && !$table->hasColumn('cover_image')) {
            $table->renameColumn('cover_url', 'cover_image');
        }

        if (!$table->hasColumn('gallery')) {
            $table->addColumn('gallery', 'json', [
                'null' => true,
                'comment' => '图片集',
                'after' => 'cover_image',
            ]);
        }

        if (!$table->hasColumn('videos')) {
            $table->addColumn('videos', 'json', [
                'null' => true,
                'comment' => '视频集',
                'after' => 'gallery',
            ]);
        }

        if (!$table->hasColumn('default_price')) {
            $table->addColumn('default_price', 'decimal', [
                'precision' => 12,
                'scale' => 2,
                'default' => 0,
                'comment' => '默认价格',
                'after' => 'summary',
            ]);
        }

        if (!$table->hasColumn('default_stock')) {
            $table->addColumn('default_stock', 'integer', [
                'default' => 0,
                'comment' => '默认库存',
                'after' => 'default_price',
            ]);
        }

        if (!$table->hasColumn('unit')) {
            $table->addColumn('unit', 'string', [
                'limit' => 20,
                'default' => '',
                'comment' => '计量单位',
                'after' => 'default_stock',
            ]);
        }

        if (!$table->hasColumn('min_order_qty')) {
            $table->addColumn('min_order_qty', 'integer', [
                'default' => 1,
                'comment' => '最小起订量',
                'after' => 'unit',
            ]);
        }

        if (!$table->hasColumn('step_qty')) {
            $table->addColumn('step_qty', 'integer', [
                'default' => 1,
                'comment' => '订购增量',
                'after' => 'min_order_qty',
            ]);
        }

        if (!$table->hasColumn('weight_value')) {
            $table->addColumn('weight_value', 'decimal', [
                'precision' => 10,
                'scale' => 3,
                'default' => 0,
                'comment' => '重量',
                'after' => 'step_qty',
            ]);
        }

        if (!$table->hasColumn('weight_unit')) {
            $table->addColumn('weight_unit', 'string', [
                'limit' => 10,
                'default' => '',
                'comment' => '重量单位',
                'after' => 'weight_value',
            ]);
        }

        foreach (['size_length' => '长度', 'size_width' => '宽度', 'size_height' => '高度'] as $column => $comment) {
            if (!$table->hasColumn($column)) {
                $table->addColumn($column, 'decimal', [
                    'precision' => 10,
                    'scale' => 2,
                    'default' => 0,
                    'comment' => '尺寸' . $comment,
                    'after' => $column === 'size_length' ? 'weight_unit' : ($column === 'size_width' ? 'size_length' : 'size_width'),
                ]);
            }
        }

        if (!$table->hasColumn('origin_country')) {
            $table->addColumn('origin_country', 'string', [
                'limit' => 80,
                'default' => '',
                'comment' => '产地',
                'after' => 'size_height',
            ]);
        }

        if (!$table->hasColumn('manufactured_at')) {
            $table->addColumn('manufactured_at', 'date', [
                'null' => true,
                'comment' => '生产日期',
                'after' => 'origin_country',
            ]);
        }

        if (!$table->hasColumn('description')) {
            $table->addColumn('description', 'text', [
                'null' => true,
                'comment' => '详情描述',
                'after' => 'summary',
            ]);
        }

        if (!$table->hasColumn('attachments')) {
            $table->addColumn('attachments', 'json', [
                'null' => true,
                'comment' => '附件',
                'after' => 'attributes',
            ]);
        }

        if (!$table->hasColumn('remark')) {
            $table->addColumn('remark', 'string', [
                'limit' => 255,
                'default' => '',
                'comment' => '备注',
                'after' => 'description',
            ]);
        }

        if (!$table->hasColumn('views')) {
            $table->addColumn('views', 'integer', [
                'default' => 0,
                'comment' => '浏览次数',
                'after' => 'status',
            ]);
        }

        if (!$table->hasColumn('favorites')) {
            $table->addColumn('favorites', 'integer', [
                'default' => 0,
                'comment' => '收藏次数',
                'after' => 'views',
            ]);
        }

        if (!$table->hasColumn('publish_time')) {
            $table->addColumn('publish_time', 'timestamp', [
                'null' => true,
                'comment' => '上架时间',
                'after' => 'favorites',
            ]);
        }

        $table->update();

        $this->syncNewColumnsFromLegacy();
    }

    public function down(): void
    {
        $table = $this->table('prod');

        if ($table->hasColumn('publish_time')) {
            $table->removeColumn('publish_time');
        }
        if ($table->hasColumn('favorites')) {
            $table->removeColumn('favorites');
        }
        if ($table->hasColumn('views')) {
            $table->removeColumn('views');
        }
        if ($table->hasColumn('remark')) {
            $table->removeColumn('remark');
        }
        if ($table->hasColumn('attachments')) {
            $table->removeColumn('attachments');
        }
        if ($table->hasColumn('description')) {
            $table->removeColumn('description');
        }
        if ($table->hasColumn('manufactured_at')) {
            $table->removeColumn('manufactured_at');
        }
        if ($table->hasColumn('origin_country')) {
            $table->removeColumn('origin_country');
        }
        foreach (['size_height', 'size_width', 'size_length'] as $column) {
            if ($table->hasColumn($column)) {
                $table->removeColumn($column);
            }
        }
        if ($table->hasColumn('weight_unit')) {
            $table->removeColumn('weight_unit');
        }
        if ($table->hasColumn('weight_value')) {
            $table->removeColumn('weight_value');
        }
        if ($table->hasColumn('step_qty')) {
            $table->removeColumn('step_qty');
        }
        if ($table->hasColumn('min_order_qty')) {
            $table->removeColumn('min_order_qty');
        }
        if ($table->hasColumn('unit')) {
            $table->removeColumn('unit');
        }
        if ($table->hasColumn('default_stock')) {
            $table->removeColumn('default_stock');
        }
        if ($table->hasColumn('default_price')) {
            $table->removeColumn('default_price');
        }
        if ($table->hasColumn('videos')) {
            $table->removeColumn('videos');
        }
        if ($table->hasColumn('gallery') && !$table->hasColumn('cover_url')) {
            // keep gallery column
        }
        if ($table->hasColumn('cover_image') && !$table->hasColumn('cover_url')) {
            $table->renameColumn('cover_image', 'cover_url');
        }
        if ($table->hasColumn('model')) {
            $table->removeColumn('model');
        }
        if ($table->hasColumn('subtitle')) {
            $table->removeColumn('subtitle');
        }
        if ($table->hasColumn('title') && !$table->hasColumn('name')) {
            $table->renameColumn('title', 'name');
        }
        if ($table->hasColumn('sku_code') && !$table->hasColumn('spu_code')) {
            if ($table->hasIndex(['sku_code'])) {
                $table->removeIndex(['sku_code']);
            }
            $table->renameColumn('sku_code', 'spu_code');
            $table->addIndex(['spu_code'], ['unique' => true, 'name' => 'spu_code']);
        }
        if ($table->hasColumn('region_id')) {
            $table->removeColumn('region_id');
        }
        if ($table->hasColumn('seller_user_id')) {
            $table->removeColumn('seller_user_id');
        }
        if ($table->hasColumn('seller_org_id') && !$table->hasColumn('org_id')) {
            $table->renameColumn('seller_org_id', 'org_id');
        }

        $table->update();
    }

    private function syncNewColumnsFromLegacy(): void
    {
        $rows = Db::name('prod')
            ->field(['id', 'summary', 'title', 'sku_code'])
            ->select()
            ->toArray();

        foreach ($rows as $row) {
            $updates = [];

            if (($row['title'] ?? '') === '' && isset($row['summary']) && $row['summary'] !== '') {
                $updates['title'] = $row['summary'];
            }

            if (($row['sku_code'] ?? '') === '') {
                $updates['sku_code'] = sprintf('SKU%06d', (int) $row['id']);
            }

            if ($updates !== []) {
                Db::name('prod')
                    ->where('id', (int) $row['id'])
                    ->update($updates);
            }
        }
    }
}
